package com.yq.front.action;

import com.yq.front.service.UserFrontService;
import com.yq.front.util.ViewPathConstants;
import com.yq.front.vo.UserVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;

/**
 * Created by yq on 16-5-26.
 */
@SessionAttributes("currentUser")
@Controller("indexAction")
public class UserAction {
    private static final Log log = LogFactory.getLog(UserAction.class);

    @Resource(name = "userFrontService")
    private UserFrontService userFrontService;
    /**
     * 转向添加用户页面
     * */
    @RequestMapping("gotoAddUser.do")
    public String gotoAddUser(){
        return ViewPathConstants.ADD_USER_PAGE;
    }

    /**
     * 添加用户
     * */
    @RequestMapping("addUser.do")
    public ModelAndView addUser(UserVO userVO){
        ModelAndView modelAndView = new ModelAndView();

        try {
            userFrontService.addUser(userVO);
        } catch (Exception e) {
            modelAndView.setViewName(ViewPathConstants.ERROR_PAGE);
            modelAndView.addObject("msg", e.getMessage());
            log.error(e.getMessage(), e);
            return modelAndView;
        }

        modelAndView.addObject("user", userVO);
        modelAndView.setViewName(ViewPathConstants.ADD_USER_SUCCESS);
        return modelAndView;
    }

    /**
     * 转到修改用户页
     * */
    @RequestMapping("gotoUpdateUser.do")
    public String gotoUpdateUser(){
        return ViewPathConstants.UPDATE_USER_PAGE;
    }

    /**
     * 修改用户信息
     * @param currentUser 当前登陆的用户信息
     * */
    @RequestMapping("updateUser.do")
    public ModelAndView updateUser(@ModelAttribute("currentUser") UserVO currentUser, ModelAndView modelAndView){
        try {
            userFrontService.updateUser(currentUser);
            modelAndView.setViewName(ViewPathConstants.UPDATE_USER_PAGE);
            modelAndView.addObject("msg", "修改成功");
        } catch (Exception e) {
            modelAndView.setViewName(ViewPathConstants.ERROR_PAGE);
            modelAndView.addObject("msg", e.getMessage());
            log.error(e.getMessage(), e);
            return modelAndView;
        }

        return modelAndView;
    }
}
